package com.eshipenet.shipnet.equipmentdatahub

import org.joda.time.Period
import play.api.libs.json._

import scala.util.Try

object EquipmentModel {

  implicit val jodaDateTimeReads: Reads[Period] = Reads[Period] {
    case JsString(str) => JsSuccess(Period.parse(str))
    case JsNumber(num) => JsSuccess(Period.millis(num.toInt))
    case other         => JsError(s"invalid Period format: $other")
  }

  implicit val jodaDateTimeWrites: Writes[Period] = (o: Period) => JsString(o.toString())

  def apply(raw: JsValue): Try[EquipmentModel] = Try {
    val id     = (raw \ "id").as[String]
    val period = (raw \ "period").as[Period]
    val instData = raw \ "instData" match {
      case JsDefined(JsString(s)) => Json.parse(s).as[Map[String, EquipmentModelDatumSchema]]
      case JsDefined(x: JsObject) => x.as[Map[String, EquipmentModelDatumSchema]]
      case other                  => throw new Exception(s"invalid data field: ${other}")
    }
    EquipmentModel(id, period, instData, raw)
  }

}

case class EquipmentModel(id: String, period: Period, instData: Map[String, EquipmentModelDatumSchema], raw: JsValue)
